package com.scheduler.utils.thread;

import com.scheduler.utils.trace.Slf4jMdcUtil;

import java.util.concurrent.*;


public class TraceThreadPoolExecutor extends ThreadPoolExecutor {


    public TraceThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
                                   BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
                                   RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }

    @Override
    public void execute(Runnable runnable) {
        // 加载当前主线程的RpcContext
        String traceId = Slf4jMdcUtil.traceId();
        super.execute(() -> {
            try {
                Slf4jMdcUtil.appendMDCWithTraceId(traceId);
                runnable.run();
            } finally {
                // 线程执行完成前清理RpcContext
                Slf4jMdcUtil.clearMDCAndComplete();
            }
        });
    }
}
